package com.lc.springboot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lengchuan <lishuijun1992@gmail.com>
 * @date 16-8-24
 */
@Controller
public class HomeController {

    @RequestMapping("/tologin")
    @ResponseBody
    public String toLogin(){

        return "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>登录</title>\n" +
                "</head>\n" +
                "<body>\n" +
                "    <form action=\"/login\" method=\"post\">\n" +
                "        用户名：<input type=\"text\" name=\"loginName\"><br>\n" +
                "        密码： <input type=\"password\" name=\"password\"><br>\n" +
                "                <input type=\"submit\" value=\"登录\">\n" +
                "    </form>\n" +
                "</body>\n" +
                "</html>";
    }

    /**
     * 登录
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public String login(HttpServletRequest request, RedirectAttributes rediect) {
        String loginName = request.getParameter("loginName");
        String password = request.getParameter("password");

        UsernamePasswordToken upt = new UsernamePasswordToken(loginName, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(upt);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return "您的账号或密码输入错误!";
            //TODO 其它异常的接收
        }
        return "登录成功";
    }

    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping("/logout")
    @ResponseBody
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "已退出";
    }


    @RequestMapping("/unauthorized")
    @ResponseBody
    public String unauthorized() {

        return "unauthorized...";
    }
}
